const db = wx.cloud.database()
const _ = db.command
//引入封装的watch监听文件
const watch = require('../../utils/watch.js')
const account = wx.getStorageSync('userInfo').account
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectAll:false,
    allPrice:0,
    productSelected:[],
    cartIsNull:false
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(app.golbalData.isLogin) this.init()
  },

  //前往商品详情
  toProductDetail(e){
    let productInfo = e.currentTarget.dataset.productinfo
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?productInfo='+JSON.stringify(productInfo),
    })
  },
  /**
   * 数据初始化
   */
  init(){
    wx.showLoading({
      title: '加载中...',
      
    })

    //shoppingCart表示购物车中的商品，为数组类型
    this.getCloudData().then(res=>{
      let shoppingCart = res.data[0].products
      let id = res.data[0]._id

      if(shoppingCart.length != 0){
        let {productSelected} = this.data 
        for(let index in shoppingCart){
          productSelected.push(false)
        }
        this.setData({
          shoppingCart,
          id,
          cartIsNull:false,
          productSelected,
        })
      }else{
        this.setData({
          cartIsNull:true
        })
      }
      wx.hideLoading({
      })
    }).catch(error=>{
      wx.hideLoading({
      })
      this.setData({
        cartIsNull:true
      })
    })
  },

  /**
   * 获取云端购物车数据
   */
  getCloudData(){
    let account = wx.getStorageSync('userInfo').account

    return db.collection('shoppingCart').where({
      account
    }).get()
  },


  watch: {
    allPrice: function(newValue,oldValue) {
        console.log(newValue,oldValue);
    },
  },

  changeSelection(e){
    //改变商品选中状态
    let index = e.currentTarget.id
    let selected = this.data.productSelected[index]
    let {productSelected,allPrice,selectAll} = this.data

    productSelected.splice(index,1,!selected)

    //改变合计总价格
    let {price,quantity} = e.currentTarget.dataset.productinfo
    let productsPrice = parseFloat((parseFloat(price)*quantity).toFixed(2))
    if(!selected){
      //商品选中
      allPrice += productsPrice
    }else{
      //商品未选中
      allPrice -= productsPrice
      selectAll = false
    }
    allPrice = parseFloat(allPrice.toFixed(2))

    this.setData({
      productSelected,
      allPrice,
      selectAll,
    })
  },

  selectAll(){
    //修改商品选中状态
    let {selectAll,productSelected,shoppingCart,allPrice} = this.data

    let newProductSelected = productSelected.map((item)=>{
      return !selectAll
    })

    this.setData({
      selectAll:!selectAll,
      productSelected:newProductSelected,
    })
    
    //计算总价格
    if(!selectAll){
      //全选中
      for(let index in shoppingCart){
        let p = shoppingCart[index]
        let productsPrice = parseFloat((parseFloat(p.price)*p.quantity).toFixed(2))
        allPrice += productsPrice
      }
    }else{
      //取消选中
      for(let index in shoppingCart){
        let p = shoppingCart[index]
        let productsPrice = parseFloat((parseFloat(p.price)*p.quantity).toFixed(2))
        allPrice -= productsPrice
      }
    }

    allPrice = parseFloat(allPrice.toFixed(2))
    this.setData({
      allPrice,
    })
  },

  //减少商品数量
  quantityminus(e){
    wx.showLoading({
      title: '更改中...',
      mask:true,
    })
    let {id} = this.data
    let productInfo = e.currentTarget.dataset.productinfo
    if((productInfo.quantity-1) == 0){
      wx.showToast({
        title: '到底啦，亲~',
        icon:'none'
      })
      wx.hideLoading()
    }else{
      db.collection('shoppingCart').where({
        account
      }).get().then(res=>{
        let products = res.data[0].products
        let filProduct = products.filter((p)=>{
          return p._id.indexOf(productInfo._id) != -1
        })
        filProduct[0].quantity--
        db.collection('shoppingCart').doc(id).update({
          data:{
            products,
          }
        }).then(()=>{
          this.init()
          wx.hideLoading()
          wx.showToast({
            title: '更改成功，亲~',
            icon:'success'
          })
        }).catch(error=>{
          console.error(error)
        })
      }).catch(error=>{
        console.log(error)
      })

    }
  },

  //增加商品数量
  quantityplus(e){
    wx.showLoading({
      title: '更改中...',
      mask:true,
    })
    let {id} = this.data
    let productInfo = e.currentTarget.dataset.productinfo
    
    db.collection('shoppingCart').where({
      account
    }).get().then(res=>{
      let products = res.data[0].products
      let filProduct = products.filter((p)=>{
        return p._id.indexOf(productInfo._id) != -1
      })
      filProduct[0].quantity++
      db.collection('shoppingCart').doc(id).update({
        data:{
          products,
        }
      }).then(()=>{
        this.init()
        wx.hideLoading()
        wx.showToast({
          title: '更改成功，亲~',
          icon:'success'
        })
      }).catch(error=>{
        console.error(error)
      })
    }).catch(error=>{
      console.log(error)
    })
  },

  //结算
  getAllPrice(){
    //获取选中的商品列表
    let {productSelected,shoppingCart,allPrice} = this.data
    let selectedProducts = [] // 表示已选中的商品
    for(let index in shoppingCart){
      if(productSelected[index]){
        selectedProducts.push(shoppingCart[index])
      }
    }

    if(selectedProducts.length != 0){
    //跳转至生成订单页面
      wx.navigateTo({
        url: '/pages/createOrder/createOrder?selectedProducts='+JSON.stringify(selectedProducts)+'&allPrice='+allPrice,
      })
    }
  },

 
})